<template>
  <div class="menu">
    <div class="top">
      <queryInput
        id="name"
        name="菜单名称"
        :value="query.name"
        @update:value="handleUpdate"
      />
      <queryInput
        id="platform"
        name="所属平台"
        type="select"
        :value="query.platform"
        :option="optionType"
        @update:value="handleUpdate"
      />
      <div>
        <el-button type="primary" @click="handle_query">查询</el-button>
        <el-button @click="handle_resetting">重置</el-button>
      </div>
    </div>
    <div class="cont">
      <div class="cont_top">
        <div class="total_box">
          菜单总计：
          <span>{{ total }}</span>
        </div>
        <div class="operate">
          <el-button
            type="primary"
            @click="handle_drawer()"
            v-if="route.meta.add"
          >
            新建
          </el-button>
        </div>
      </div>
      <el-table
        v-loading="loading"
        style="height: 100%"
        :data="tableData"
        show-overflow-tooltip
        :header-cell-style="{
          backgroundColor: '#f7f8fa',
          color: '#8c8c8c',
          fontWeight: 400,
          cursor: 'pointer',
        }"
        :cell-style="{ color: '#000' }"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <template #empty>
          <el-empty :image-size="100" description="暂无数据" />
        </template>
        <el-table-column type="index" label="序号" width="100" align="center">
          <template #default="scope">{{ scope.row.pid }}</template>
        </el-table-column>
        <el-table-column prop="menuName" label="菜单名称" />
        <el-table-column prop="menuUrl" label="菜单路径">
          <template #default="scope">
            <a
              target="_blank"
              :href="
                scope.row.menuType == 1
                  ? scope.row.menuUrl
                  : ssptAddr(scope.row.platformId) + scope.row.menuUrl
              "
            >
              {{
                scope.row.menuType == 1
                  ? scope.row.menuUrl
                  : ssptAddr(scope.row.platformId) + scope.row.menuUrl
              }}
            </a>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="菜单排序" />
        <el-table-column prop="platformId" label="所属平台">
          <template #default="scope">{{ sspt(scope.row.platformId) }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handle_drawer(scope.row)"
              v-if="route.meta.edit"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              @click="handle_del(scope.row.id)"
              v-if="route.meta.del"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="cont_button">
        <el-pagination
          v-model:current-page="pageNo"
          v-model:page-size="pageSize"
          :page-sizes="[15, 20, 30, 40]"
          layout="->,slot, sizes, prev, pager, next, jumper"
          :total="total"
          @change="handle_page"
        >
          <div class="total">共{{ Math.ceil(total / pageSize) }}页</div>
        </el-pagination>
      </div>
    </div>
    <!-- 新建/编辑 -->
    <el-drawer
      custom-class="drawer"
      size="36%"
      v-model="drawerVisible"
      :show-close="false"
      :with-header="false"
      :close-on-click-modal="false"
    >
      <div class="drawer_header">
        <h3>{{ drawerTitle }}</h3>
        <Close
          style="width: 20px; height: 20px; cursor: pointer"
          @click="cancel_drawer(drawerForm)"
        />
      </div>
      <div class="drawer_cont">
        <subtitle title="基础信息" />
        <el-form
          ref="drawerForm"
          class="drawerForm"
          :model="drawerform"
          :rules="drawerRules"
          label-width="auto"
          scroll-to-error
        >
          <el-form-item label="所属平台" prop="platformId">
            <el-select
              :disabled="drawerTitle !== '新建菜单'"
              v-model="drawerform.platformId"
              filterable
              placeholder="请选择"
              @change="get_ptcd"
            >
              <el-option
                v-for="item in optionType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="父级菜单" prop="parentId">
            <el-tree-select
              :disabled="drawerTitle !== '新建菜单'"
              v-model="drawerform.parentId"
              :data="menuData"
              :props="parentIdProps"
              :render-after-expand="false"
              check-strictly
              filterable
            />
          </el-form-item>
          <el-form-item label="菜单编号" prop="menuId">
            <el-input
              v-model="drawerform.menuId"
              placeholder="请输入"
              :disabled="drawerTitle !== '新建菜单'"
            />
          </el-form-item>
          <el-form-item label="菜单名称" prop="menuName">
            <el-input v-model="drawerform.menuName" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="菜单类型" prop="menuType">
            <el-select v-model="drawerform.menuType" placeholder="请选择">
              <el-option label="绝对路径" value="1" />
              <el-option label="相对路径" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="菜单路径" prop="menuUrl">
            <el-input v-model="drawerform.menuUrl" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="菜单排序" prop="sort">
            <el-input
              v-model="drawerform.sort"
              placeholder="请输入"
              @input="
                (value) => (drawerform.sort = value.replace(/[^0-9]/g, ''))
              "
            />
          </el-form-item>
          <div class="drawer_operate">
            <el-button @click="cancel_drawer(drawerForm)">取消</el-button>
            <el-button type="primary" @click="confirm_drawer(drawerForm)">
              确认
            </el-button>
          </div>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>
  
  <script setup>
import subtitle from "@/components/subtitle.vue";
import {
  addMenu,
  deleteMenu,
  getSonMenu,
  menuPage,
  sysPage,
  updateMenu,
} from "@/api/appPlatfor";
import { onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useStore } from "@/store/index";
import { useRoute } from "vue-router";

const store = useStore();
const route = useRoute();

const loading = ref(false);
const total = ref(0);
const pageNo = ref(1);
const pageSize = ref(15);
const drawerVisible = ref(false);
const drawerTitle = ref("");
const drawerForm = ref(null);
const query = reactive({
  name: "",
  platform: "",
});
const optionType = ref([]);
const tableData = ref([]);
const ssptData = ref([]);
const parentIdProps = ref({
  children: "children",
  label: "menuName",
  value: "id",
});

const menuData = ref([
  {
    id: "0",
    menuName: "-",
    children: [],
  },
]);
const drawerform = reactive({
  id: "",
  platformId: "", //必传
  menuName: "", //必传
  menuUrl: "", //必传
  menuId: "", //必传
  sort: "", //非必传
  menuType: "", //非必传
  parentId: "0", //必传
});
const drawerRules = reactive({
  platformId: [
    { required: true, message: "请选择所属平台", trigger: "change" },
  ],
  menuName: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
  menuUrl: [{ required: false, message: "请输入菜单路径", trigger: "blur" }],
  menuId: [{ required: true, message: "请输入菜单编号", trigger: "blur" }],
  sort: [{ required: false, message: "请输入菜单顺序", trigger: "blur" }],
  menuType: [{ required: true, message: "请选择菜单类型", trigger: "change" }],
  parentId: [{ required: true, message: "请选择父级菜单", trigger: "change" }],
});

//更新查询数据
const handleUpdate = ({ key, value }) => {
  query[key] = value;
  if (!value) {
    get_menuPage();
  }
};
//查询
const handle_query = () => {
  get_menuPage();
};
//查询 - 重置
const handle_resetting = () => {
  query.name = "";
  query.platform = "";
  get_menuPage();
};

//编辑/新建
const handle_drawer = (data) => {
  if (!data) {
    //新建
    drawerTitle.value = "新建菜单";
    drawerVisible.value = true;
  } else {
    //编辑
    get_ptcd(drawerform.platformId)
    Object.assign(drawerform, data);
    drawerTitle.value = "菜单编辑";
    drawerVisible.value = true;
  }
};

//取消 -- 新建/编辑
const cancel_drawer = (formEl) => {
  menuData.value = [];
  formEl.resetFields();
  drawerVisible.value = false;
  drawerTitle.value = "";
  drawerform.platformId = "";
  drawerform.menuName = "";
  drawerform.menuUrl = "";
  drawerform.menuId = "";
  drawerform.sort = "";
  drawerform.menuType = "";
  drawerform.parentId = "";
};
//确认提交 -- 新建/编辑
const confirm_drawer = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm(
        `确定${drawerTitle.value}吗？`,
        `${drawerTitle.value}`,
        {
          type: "warning",
          distinguishCancelAndClose: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        }
      )
        .then(async () => {
          if (drawerTitle.value === "新建菜单") {
            const res = await addMenu({
              platformId: drawerform.platformId, //必传
              menuName: drawerform.menuName, //必传
              menuUrl: drawerform.menuUrl, //必传
              menuId: drawerform.menuId, //必传
              sort: drawerform.sort, //非必传
              menuType: drawerform.menuType, //非必传
              parentId: drawerform.parentId, //必传
            });
            if (res.code === 200) {
              ElMessage({
                type: "success",
                message: res.msg,
              });
            } else {
              ElMessage({
                type: "error",
                message: res.msg,
              });
            }
          } else if (drawerTitle.value === "菜单编辑") {
            const res = await updateMenu({
              id: drawerform.id,
              platformId: drawerform.platformId,
              menuName: drawerform.menuName,
              menuUrl: drawerform.menuUrl,
              menuId: drawerform.menuId,
              sort: drawerform.sort,
              menuType: drawerform.menuType,
              parentId: drawerform.parentId,
            });
            if (res.code === 200) {
              ElMessage({
                type: "success",
                message: res.msg,
              });
            } else {
              ElMessage({
                type: "error",
                message: res.msg,
              });
            }
          }
          get_menuPage();
          formEl.resetFields();
          drawerVisible.value = false;
        })
        .catch(() => {});
    } else {
      console.log("error submit!");
    }
  });
};
//删除
const handle_del = (id) => {
  ElMessageBox.confirm("确定删除该菜单吗？", {
    type: "error",
    distinguishCancelAndClose: true,
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  })
    .then(async () => {
      const res = await deleteMenu({ id: id });

      if (res.code === 200) {
        ElMessage({
          type: "success",
          message: res.msg,
        });
        get_menuPage();
      } else {
        ElMessage({
          type: "error",
          message: res.msg,
        });
      }
    })
    .catch(() => {});
};

//分页
const handle_page = (currentPage, pageSize) => {
  get_menuPage();
};

//获取所属单位
const sspt = (id) => {
  let name = "-";
  ssptData.value.forEach((item) => {
    if (item.platformId === id) {
      name = item.platformName;
    }
  });
  return name;
};
const ssptAddr = (id) => {
  let addr = "-";
  ssptData.value.forEach((item) => {
    if (item.platformId === id) {
      addr = item.platformAddress;
    }
  });
  return addr;
};
const get_sspt = async () => {
  const res = await sysPage();
  if (res.code === 200) {
    ssptData.value = res.data.data;
    res.data.data.forEach((item) => {
      optionType.value.push({
        value: item.platformId,
        label: item.platformName,
      });
    });
  }
};

//获取所属平台菜单
const get_ptcd = async (value) => {
  const res = await menuPage({
    platformId: value,
  });
  if (res.code === 200) {
    menuData.value = [
      {
        id: "0",
        menuName: "-",
        children: [],
      },
      ...res.data.data,
    ];
    menuData.value.forEach(async (item) => {
      const child = await get_getSonMenu(item.id);
      if (child.code === 200) {
        item.children = child.data;
      }
    });
  }
};
//获取菜单
let time = ref(null);
const get_menuPage = async () => {
  loading.value = true;
  const res = await menuPage({
    page: pageNo.value,
    pageSize: pageSize.value,
    menuName: query.name,
    platformId: query.platform,
  });

  time.value = setTimeout(() => {
    loading.value = false;
  }, 5000);

  if (res.code === 200) {
    clearTimeout(time.value); // 清除定时器
    time.value = null;
    total.value = res.data.count;
    tableData.value = res.data.data;
    tableData.value.forEach(async (item) => {
      const child = await get_getSonMenu(item.id);
      if (child.code === 200) {
        item.children = child.data;
      }
    });
    loading.value = false;
  }
};

const get_getSonMenu = async (id) => {
  const res = await getSonMenu({
    id: id,
  });
  return res;
};

onMounted(() => {
  get_menuPage();
  get_sspt();
});
</script>
  
  <style lang="scss" scoped>
.menu {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;
  .top {
    width: 100%;
    padding: 10px;
    background: #fff;
    display: flex;
    flex-wrap: wrap;
    gap: 30px;

    > div {
      width: calc((100% - (6 - 1) * 30px) / 4);
      height: 40px;
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }
  .cont {
    flex: 1;
    padding: 10px;
    background: #fff;
    display: flex;
    flex-direction: column;
    .cont_top {
      width: 100%;
      height: 40px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .total_box {
        display: flex;
        > span {
          font-weight: bold;
          margin: 0 20px 0 5px;
        }
        p > span {
          margin: 0 5px;
          color: #09f;
        }
      }

      .operate {
        display: flex;
        gap: 10px;
      }
    }

    .cont_button {
      width: 100%;
      height: 40px;
      margin-top: 10px;
      display: flex;
      justify-content: end;
      align-items: center;
    }
  }
}

.el-table {
  max-height: 650px;
  .table_name {
    color: #09f;
    cursor: pointer;
  }
  .el-button {
    margin: 0 8px;
  }
}

.drawer_header {
  width: 100%;
  height: 60px;
  border-bottom: 1px solid #ccc;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px;
  h3 {
    font-size: 20px;
    cursor: pointer;
  }
}

.drawer_cont {
  padding: 5px 15px;
  width: 100%;
  display: flex;
  flex-direction: column;
  .drawerForm {
    padding: 15px 0;
    // display: flex;
    // flex-wrap: wrap;
    // gap: 15px;
    // .el-form-item {
    //   width: calc(50% - 10px);
    //   width: 100%;
    // }
  }
}

.drawer_operate {
  display: flex;
  justify-content: end;
  gap: 10px;
}

.el-button {
  margin: 0;
}
</style>